package de.dopichaj.labrador.util.io.huffman;

import java.io.IOException;
import java.math.BigInteger;
import java.util.Map;

import de.dopichaj.labrador.util.io.BitInputStream;
import de.dopichaj.labrador.util.io.BitOutputStream;
import de.dopichaj.labrador.util.io.huffman.HuffmanTree.HuffmanCode;


/**
 * A node in the Huffman tree.
 * 
 * This can either be a leaf node (one of the symbols to encode) or an inner
 * node.
 */
public abstract class HuffmanNode<T> implements Comparable<HuffmanNode<T>> {
    
    private final int count;
    
    /**
     * @param count the occurrence count of this node
     */
    protected HuffmanNode(final int count) {
        this.count = count;
    }
    
    /**
     * Get the occurrence count of this node.
     */
    public int getCount() {
        return count;
    }

    /**
     * Read the symbol from the stream.
     */
    public abstract T read(final BitInputStream input) throws IOException;
    /**
     * Write the node to the given output stream, using the given data writer.
     */
    public abstract void write(final BitOutputStream output, final HuffmanDataWriter<T> writer) throws IOException;
    
    /**
     * Add the subtree to the given code map.
     */
    public abstract void addToCodeMap(final Map<T, HuffmanCode> map, BigInteger code, int significantBits);

    /**
     * Compare two {@link HuffmanNode}s by count alone; the node with the lower
     * count is smaller than the node with the higher count. Nodes with the
     * same count are considered equal (but note that this implementation is
     * inconsistent with the {@link #equals(Object)} method!).
     */
    public int compareTo(HuffmanNode<T> o) {
        return count < o.count
            ? -1
            : count > o.count
                ? 1
                : 0;
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/